import Sequelize from 'sequelize';
import express from 'express';
import { statusList, sequelizeStatus } from '../../common/status'; // 状态码对照
import { Message, User } from '../../modal/index'; // 数据库实体类
import { checkPermission } from '../../utils/utils'; // 工具类

const router = express.Router();
const permission = ["all"];

router.post('/', async function (Request, Response, next) {
  // Message.sync()
  //权限校验
  await checkPermission(Request, Response, permission)
  let param = Request.body;
  let uid = JSON.parse(Request.signedCookies.token).uid
  let querySql = {
    [Sequelize.Op.and]: []
  }
  querySql[Sequelize.Op.and].push({
    getterId: {
      [Sequelize.Op.eq]: uid
    }
  })
  param.title && querySql[Sequelize.Op.and].push({
    title: {
      [Sequelize.Op.like]: `%${param.title}%`
    }
  })
  param.status && querySql[Sequelize.Op.and].push({
    status: {
      [Sequelize.Op.eq]: param.status
    }
  })
  Message.Modal.findAndCountAll({
    where: querySql,
    offset: (param.pageNo - 1) * param.pageSize,
    limit: param.pageSize, // 分页参数
    order: Sequelize.literal('createdAt DESC'), // 排序
    include: [{
      model: User.Modal,
      as: 'getter',
      attributes: ['username']
    }, {
      model: User.Modal,
      as: 'sender',
      attributes: ['username']
    }], // 表关联
    distinct: true //去重，表关联时需要
  }).then(res => {
    Response.json({
      data: {
        list: res.rows,
        total: res.count,
      },
      message: "success"
    });
  }).catch(err => {
    console.log(err)
    Response.status(500).send({ message: sequelizeStatus[err.name] || statusList[500] || err.name });
  });
});

module.exports = router;

// 创建新记录
// for (let i = 0; i <= 50; i++) {
//   Message.create(
//     {
//       title: "代办消息标题" + String(i),
//       content: "代办消息详情" + String(i),
//       sender: "消息发送者" + String(i),
//       getter: "消息接收者" + String(i),
//       type: "message",
//       href: "www.baidu.com",
//       status: 1,
//       star: i % 2,
//       read: i % 2,
//     }
//   );
// }